#!/usr/bin/env bash
SCRIPT_DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
set -x
#ref https://www.craft.do/s/8V5RkxZDNaqOI9
#ref https://www.v2ex.com/t/908245
#ref https://v2ex.com/t/907272
# 字典来源：谷歌搜索 MDX 牛津字典

fileurl='https://mdx.mdict.org/%E6%8C%89%E8%AF%8D%E5%85%B8%E8%AF%AD%E7%A7%8D%E6%9D%A5%E5%88%86%E7%B1%BB/%E8%8B%B1%E8%AF%AD/%E6%99%AE%E9%80%9A%E8%AF%8D%E5%85%B8/%5B%E8%8B%B1-%E6%B1%89%5D/%5B%E8%8B%B1-%E6%B1%89%5D%20%E2%97%86%E3%80%90%E6%9C%97%E6%96%87%E5%BD%93%E4%BB%A3%E8%8B%B1%E8%AF%AD%E8%AF%8D%E5%85%B8%E8%8B%B1%E6%B1%89%E5%8F%8C%E8%A7%A3%E7%AC%AC4%E7%89%88%E3%80%91%E3%80%90%E5%AD%A4%E9%9B%B7%E6%8E%92%E7%89%88-%E5%BA%86%E5%A4%A7%E8%BF%90%E4%B8%93%E7%89%88%E3%80%91%E3%80%902011.8.12%E3%80%91%E5%B7%B2%E5%B0%8F%E6%94%B92011.8.15.mdx'
filename_withext=$(basename ${fileurl})
filename=${filename_withext%.*}
fileext=${filename_withext##*.}

if [ -f vpython.temp/bin/activate  ] ;then
  source vpython.temp/bin/activate
else
  virtualenv vpython.temp
fi
(
unset HTTP_PROXY
unset HTTPS_PROXY
unset FTP_PROXY
unset RSYNC_PROXY
unset ALL_PROXY
pip3 install pysocks
)

pip3 install lxml beautifulsoup4 html5lib prompt_toolkit
export LZO_PREFIX=$(brew --prefix)/opt/lzo
export LZO_PREFIX=$(brew --prefix lzo)
export C_INCLUDE_PATH=${LZO_PREFIX}/include:${LZO_PREFIX}/include/lzo
export LIBRARY_PATH=${LZO_PREFIX}/lib
pip3 install python-lzo

mkdir -p wk.temp && cd wk.temp && (
[ -d  pyglossary ] || git clone --depth=1 https://github.com/ilius/pyglossary
[ -d Dictionary-Development-Kit ] || git clone --depth=1 https://github.com/SebastianSzturo/Dictionary-Development-Kit
cp ../_build_dict.sh Dictionary-Development-Kit/bin/build_dict.sh
[ -f dictin.mdx ] || wget ${fileurl} -O dictin.${fileext}
[ -d dictout ] || python pyglossary/pyglossary.pyw --write-format=AppleDict dictin.${fileext} dictout
sed -i '' 's/ adj:=""//g' wk.temp/dictout/dictout.xml
export DICT_BUILD_TOOL_DIR=`pwd`/Dictionary-Development-Kit
(cd dictout && make V=1 DICT_BUILD_TOOL_DIR=${DICT_BUILD_TOOL_DIR})
)
